import 'package:flutter/material.dart';

class WuZiQi2 extends StatefulWidget {
  const WuZiQi2({super.key});

  @override
  State<WuZiQi2> createState() => _WuZiQi2State();
}

class _WuZiQi2State extends State<WuZiQi2> {
  List<Widget> qiju = [];
  List<List> bcpiece = [];
  List<List> bcblackPiece = [];
  List<List> bcWhitePiece = [];
  @override
  Widget build(BuildContext context) {
    List<Offset> piece = <Offset>[]; //所有棋子的集合
    List<Offset> blackPiece = <Offset>[]; //黑棋集合
    List<Offset> WhitePiece = <Offset>[]; //

    double sWidth = MediaQuery.of(context).size.width;
    double sHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      body: DecoratedBox(
        decoration: BoxDecoration(color: Colors.white),
        child: Stack(
          children: [
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  RepaintBoundary(
                    child: CustomPaint(
                      size: Size(300, 300),
                      painter: QiPan(),
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Center(
                    child: Row(
                      children: [
                        GestureDetector(
                          onTap: () {
                            if (piece.length > 2) {
                              print(piece);
                              if (piece.length % 2 == 0) {
                                //白
                                WhitePiece.removeLast();
                                piece.removeLast();
                                QiZi(offset: piece);
                              } else {
                                blackPiece.removeLast();
                                piece.removeLast();
                                QiZi(offset: piece);
                              }
                              piece.clear();
                              blackPiece.clear();
                              WhitePiece.clear();

                              setState(() {});
                            }
                          },
                          child: StatefulBuilder(
                            builder:
                                (BuildContext context, StateSetter setState) {
                              return Container(
                                width: 120,
                                height: 50,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(25),
                                    color: Colors.blue),
                                child: Center(child: Text('悔棋')),
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
            Positioned(
              bottom: 0,
              right: 0,
              child: GestureDetector(
                onTap: () {
                  bcpiece.add(piece);
                  bcWhitePiece.add(WhitePiece);
                  bcblackPiece.add(bcblackPiece);
                  qiju.add(qijuBox());
                  setState(() {});
                  print(qiju);
                  print(bcpiece);
                },
                child: Container(
                  alignment: Alignment.bottomRight,
                  margin: EdgeInsets.symmetric(horizontal: 20, vertical: 100),
                  width: 120,
                  height: 50,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25),
                      color: Colors.blue),
                  child: Center(child: Text('保存棋局')),
                ),
              ),
            ),
            Positioned(
              top: 50,
              left: sWidth / 2 - 100,
              child: Container(
                alignment: Alignment.topCenter,
                width: 200,
                height: 200,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25),
                    color: Colors.blue),
                child: Column(children: qiju),
              ),
            ),
            Center(
              child: StatefulBuilder(
                  builder: (BuildContext context, StateSetter setState) {
                return Listener(
                  child: CustomPaint(
                    size: const Size(300, 300), //指定画布大小
                    painter: QiZi(offset: piece),
                  ),
                  onPointerUp: (event) {
                    print(event.localPosition);
                    print(QiZixy(event.localPosition));
                    var qizi = QiZixy(event.localPosition);
                    if (piece.contains(qizi)) {
                      print('已有棋子');
                    } else {
                      piece.add(qizi);
                      QiZi(offset: piece);
                    }
                    if (piece.length % 2 == 1) {
                      blackPiece.add(qizi);
                      if (Win(qizi, false, blackPiece)) {
                        showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) {
                              return AlertDialog(
                                title: Text("提示"),
                                content: Text("黑棋获胜"),
                                actions: [
                                  TextButton(
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        setState(() {});
                                      },
                                      child: Text("确定")),
                                  TextButton(
                                      onPressed: () {
                                        piece.clear();
                                        blackPiece.clear();
                                        WhitePiece.clear();
                                        Navigator.of(context).pop();
                                        setState(() {});
                                      },
                                      child: Text("重新开始")),
                                ],
                              );
                            });
                      }
                    } else {
                      WhitePiece.add(qizi);
                      if (Win(qizi, true, WhitePiece)) {
                        showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) {
                              return AlertDialog(
                                title: Text("提示"),
                                content: Text("白棋获胜"),
                                actions: [
                                  TextButton(
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        setState(() {});
                                      },
                                      child: Text("确定")),
                                  TextButton(
                                      onPressed: () {
                                        piece.clear();
                                        blackPiece.clear();
                                        WhitePiece.clear();
                                        Navigator.of(context).pop();
                                        setState(() {});
                                      },
                                      child: Text("重新开始")),
                                ],
                              );
                            });
                      }
                    }
                    setState(() {});
                  },
                );
              }),
            )
          ],
        ),
      ),
    );
  }

  Container qijuBox() {
    return Container(
      color: Colors.pink[100],
      padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('棋局1'),
          Row(
            children: [
              Text('应用'),
              SizedBox(
                width: 10,
              ),
              Text('删除'),
            ],
          )
        ],
      ),
    );
  }

  bool Win(Offset offset, bool qiziColor, List<Offset> offs) {
    //左
    List<Offset> l = [];
    int lLenght = 0;

    for (var x = offset.dx; x >= 0; x = x - 20) {
      var item = Offset(x, offset.dy);
      if (offs.contains(item)) {
        lLenght++;
        l.add(item);
        if (lLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    // 右
    List<Offset> r = [];
    int rLenght = 0;
    for (var x = offset.dx; x <= 300; x = x + 20) {
      var item = Offset(x, offset.dy);
      if (offs.contains(item)) {
        rLenght++;
        r.add(item);
        if (rLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    //上
    List<Offset> t = [];
    int tLenght = 0;
    for (var y = offset.dy; y >= 0; y = y - 20) {
      var item = Offset(offset.dx, y);
      if (offs.contains(item)) {
        tLenght++;
        t.add(item);
        if (tLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    //下
    List<Offset> b = [];
    int bLenght = 0;
    for (var y = offset.dy; y <= 300; y = y + 20) {
      var item = Offset(offset.dx, y);
      if (offs.contains(item)) {
        bLenght++;
        b.add(item);
        if (bLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    //左上
    List<Offset> lt = [];
    int ltLenght = 0;
    for (var y = offset.dy, x = offset.dx;
        x >= 0 && y >= 0;
        y = y - 20, x = x - 20) {
      var item = Offset(x, y);
      if (offs.contains(item)) {
        ltLenght++;
        lt.add(item);
        if (ltLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    //左下
    List<Offset> lb = [];
    int lbLenght = 0;
    for (var y = offset.dy, x = offset.dx;
        x >= 0 && y <= 300;
        y = y + 20, x = x - 20) {
      var item = Offset(x, y);
      if (offs.contains(item)) {
        lbLenght++;
        lb.add(item);
        if (lbLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    //右上
    List<Offset> rt = [];
    int rtLenght = 0;
    for (var y = offset.dy, x = offset.dx;
        x <= 300 && y > 0;
        y = y - 20, x = x + 20) {
      var item = Offset(x, y);
      if (offs.contains(item)) {
        rtLenght++;
        rt.add(item);
        if (rtLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    //右下
    List<Offset> rb = [];
    int rbLenght = 0;
    for (var y = offset.dy, x = offset.dx;
        x <= 300 && y <= 300;
        y = y + 20, x = x + 20) {
      var item = Offset(x, y);
      if (offs.contains(item)) {
        rbLenght++;
        rb.add(item);
        if (rbLenght >= 5) {
          return true;
        }
      } else {
        break;
      }
    }

    if (l.length + r.length == 6) {
      return true;
    }

    if (t.length + b.length == 6) {
      return true;
    }

    if (lt.length + rb.length == 6) {
      return true;
    }

    if (rt.length + lb.length == 6) {
      return true;
    }

    return false;
  }

  Offset QiZixy(Offset offset) {
    double ddx = 0; //最终棋子的x坐标
    double ddy = 0; //最终棋子的y坐标
    double level = 20;
    int modx = offset.dx ~/ level;
    int mody = offset.dy ~/ level;
    if (offset.dx - level * modx <= 10) {
      ddx = level * modx;
    } else {
      ddx = level * (modx + 1);
    }

    if (offset.dy - level * mody <= 10) {
      ddy = level * mody;
    } else {
      ddy = level * (mody + 1);
    }
    return Offset(ddx, ddy);
  }
}

class QiZi extends CustomPainter {
  QiZi({Key? key, required this.offset}) : super();

  late final List<Offset> offset;

  @override
  void paint(Canvas canvas, Size size) {
    print('paint ch');
    var rect = Offset.zero & size;
    //画棋子
    // drawPieces(canvas, rect);
    drawPieces1(canvas, offset);
  }

  void drawPieces1(Canvas canvas, List<Offset> offsets) {
    //画一个黑子
    var paint = Paint()
      ..style = PaintingStyle.fill
      ..color = Colors.black;
    for (var i = 0; i < offsets.length; i++) {
      //画一个黑子
      paint.color = Colors.black;
      if (i % 2 == 0) {
        //画一个黑子
        canvas.drawCircle(
          offsets[i],
          8,
          paint,
        );
      } else {
        //画一个白子
        paint.color = Colors.white;
        canvas.drawCircle(
          offsets[i],
          8,
          paint,
        );
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}

class QiPan extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    var rect = Offset.zero & size;
    drawChessboard(canvas, rect);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return false;
  }

  void drawChessboard(Canvas canvas, Rect rect) {
    //棋盘背景
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill //填充
      ..color = Color(0xFFDCC48C);
    canvas.drawRect(rect, paint);

    //画棋盘网格
    paint
      ..style = PaintingStyle.stroke //线
      ..color = Colors.black38
      ..strokeWidth = 1.0;

    //画横线
    for (int i = 0; i <= 15; ++i) {
      double dy = rect.top + rect.height / 15 * i;
      canvas.drawLine(Offset(rect.left, dy), Offset(rect.right, dy), paint);
    }

    for (int i = 0; i <= 15; ++i) {
      double dx = rect.left + rect.width / 15 * i;
      canvas.drawLine(Offset(dx, rect.top), Offset(dx, rect.bottom), paint);
    }
  }
}
